package com.mmloo.platform.controller;

import com.mmloo.common.exception.MMLOOException;
import com.mmloo.common.message.Message;
import com.mmloo.common.model.User;
import com.mmloo.common.service.UserService;
import com.mmloo.manage.service.LoginManageService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by jessy on 2015/10/19.
 */
@Controller
@RequestMapping("/")
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    LoginManageService loginManageService;

    @Autowired
    UserService userService;

    @RequestMapping(value = "login",method = RequestMethod.GET)
    public String login(){
        return "/front/login/login";
    }

    @RequestMapping(value = "register",method = RequestMethod.POST)
    @ResponseBody
    public String register(@RequestParam(value = "username",required = true)String username,
                           @RequestParam(value = "password",required = true)String password,
                           HttpServletResponse response) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>register");
        try {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userService.save(user);
            response.setHeader("Access-Control-Allow-Origin", "*");
            return new Message(true, "注册成功").toJson();
        }catch (Exception e){
            return new Message(true, "注册失败").toJson();
        }
    }

    @ResponseBody
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public String login(@RequestParam(value = "username")String username,
                        @RequestParam(value = "password")String password,
                        @RequestParam(value = "code")String loginKaptchaCode,
                        HttpServletRequest request) throws MMLOOException {
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()||subject.isRemembered()){
            return new Message(true,"登录成功").toJson();
        }
        Session shiroSession = subject.getSession();
        Object kaptchaCode = shiroSession.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        if (kaptchaCode!=null && !StringUtils.equalsIgnoreCase(loginKaptchaCode, kaptchaCode.toString()))
        {
            return new Message(false,"验证码错误!").toJson();
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username,password,false,request.getRemoteHost());
        String message = "";
        try{
            subject.login(token);
            User user = loginManageService.findByUsername(username);
            request.getSession(true).setAttribute("loginUser",user);
            return new Message(true,"登录成功").toJson();
        }catch (UnknownAccountException uae){
            logger.info("Unknown User!");
           message = "Unknown User!";
        } catch (IncorrectCredentialsException ice)
        {
            logger.info("Incorrect Password!");
           message = "Incorrect Password!";

        } catch (LockedAccountException lae)
        {
            logger.info("User Locked!");
            message = "User Locked!";

        } catch (AuthenticationException ae)
        {
            logger.info("Authentication Failed!");
            message = "Authentication Failed!";

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Message(false,message).toJson();
    }


}
